﻿using DB.From;
using DB.Main;
using Microsoft.IdentityModel.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using WebApplication1.Models;
using WebApplication1.Utils;

namespace WebApplication1.Services
{
    public class AlarmService
    {
        public MysqlSugar MysqlSugar { get; set; }

        /// <summary>
        /// 报警等级
        /// </summary>
        public enum AlarmType
        {
            /// <summary>
            /// 正常
            /// </summary>
            Normal,
            /// <summary>
            /// 只插入一次
            /// </summary>
            Once,
            /// <summary>
            /// 恢复
            /// </summary>
            Recover
        }

        public AlarmService()
        {
            MysqlSugar = new MysqlSugar("FrontEnd4.0From");
        }

        public void InsertAlarm(DB.Main.t_Alarm t_Alarm)
        {
            MyLogHelper.Debug($"开始插入数据库数据:TerminalId{t_Alarm.TerminalId}");
            //MyLogHelper.Debug(JsonConvert.SerializeObject(t_Alarm));
            try
            {
                MysqlSugar.Main.Insertable(t_Alarm).ExecuteCommand();

            }
            catch (Exception ex)
            {
                MyLogHelper.Error("数据库更新报警数据失败");

                MyLogHelper.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 取消报警
        /// </summary>
        public void CancelAlarm(string TerminalId)
        {
            var strHead = $"TerminalId[{TerminalId}]:";
            MyLogHelper.Debug($"{strHead}取消报警");
            var deviceId = Convert.ToInt64(TerminalId, 16);
            try
            {
                var model =  MysqlSugar.Main.Queryable<DB.Main.t_Alarm>()
                    .Where(t => t.deviceId == deviceId && t.Flag == -1)
                    .OrderByDescending(t => t.Id).ToList();
                if(model == null )
                {
                    MyLogHelper.Debug($"{strHead}取消报警信息不存在");

                }

                else
                {
                    foreach (var item in model)
                    {
                        item.Flag = 0;
                        item.EndTime = DateTime.Now;
                    }
                    MysqlSugar.Main.Updateable(model).ExecuteCommand();
                }
                
            }
            catch (Exception ex)
            {
                MyLogHelper.Error("数据库更新报警数据失败");

                MyLogHelper.Error(ex.ToString());
            }
        }
    }
}
